/**************************************************************************
Class Name: NMRLeadCreateExtension 
Author: Accenture
Date: 3/8/2012 
Requirement/Project Name: NMR  
Description: Sales Rep should be allowed to enter an I Fill It i Keep It lead.
             Controller for NMRIFIKICreationPage.
Version History: Updated to invoke SIL for creating a new lead.
****************************************************************************/

public class NMRLeadCreateExtension {
   
    public Id newPageId {get;set;}
    public Boolean dupLeadSameOwner {get;set;}
    public Boolean dupLeadDiffOwner {get;set;}
    public Boolean dupAccSameOwner {get;set;}
    public Boolean dupAccDiffOwner {get;set;}
    public Boolean createLead {get;set;}
    public Boolean submit{get;set;}
    public String phoneNumber{get;set;}
    public String companyName{get;set;}
    public String source{get;set;}
    public String phoneEmpty{get;set;}
    public String companyEmpty{get;set;}
    public String sourceEmpty{get;set;}
    public Boolean showError{get;set;}
    public String errorMessage{get;set;}
    private AppEndPoints__c appEndPoint = AppEndPoints__c.getInstance();
    
    //retrieving the Lead and Account record types for NMR
    public static Id nmrLeadRecordTypeID = RecordTypeHelper.GetRecordTypeID('Lead', 'NMR Lead');
    public static Id nmrLeadCustIdRecordTypeID = RecordTypeHelper.GetRecordTypeID('Lead', 'NMR Lead with CustomerId');
    public static Id nmrAccountRecordTypeID = RecordTypeHelper.GetRecordTypeID('Account', 'CSS Customer');
    
    //constructor
    public NMRLeadCreateExtension(ApexPages.StandardController controller) {
        phoneEmpty = '';
        companyEmpty = '';
        sourceEmpty = '';
        
    }
          
    /**
    * Method is invoked on the click of the submit button 
    * on the IFIKI creation web page. It verifies if Lead/Account already
    * exists and displays corresponding page. If its a fresh lead SIL is invoked
    * to create a Standardized Lead Request.
    */
    public PageReference submit() {
        dupLeadSameOwner = false;
        dupLeadDiffOwner = false;
        dupAccSameOwner = false;
        dupAccDiffOwner = false;
        createLead = false;
        Submit = true;
        PageReference pageRef = null;
        boolean check = false;
        phoneEmpty = '';
        companyEmpty = '';
        sourceEmpty = '';
        showError = false;
        
        if(inputValid()){
            validateLead();
            if(dupLeadSameOwner || dupAccSameOwner)
                pageRef = new PageReference('/'+ newPageId);
            
        }
        phoneNumber = NMRUtil.formatPhone(phoneNumber);
        return pageRef;
    }
    
    private boolean inputValid(){
        boolean valid = true;
        if(NMRUtil.isEmpty(phoneNumber)){
            phoneEmpty = 'Phone Number is mandatory.';
            valid = false;
        } else{
            phoneNumber = SilCustomerHelper.CreatePhoneNumberHash(phoneNumber);
            if(NMRUtil.isEmpty(phoneNumber) || phoneNumber.length() != 10){
                phoneEmpty = 'Invalid area code and phone number';
                valid = false;
            }
        
        }
        if(NMRUtil.isEmpty(companyName)){
            companyEmpty = 'Company Name is mandatory.';
            valid = false;
        }
        if (NMRUtil.isEmpty(source)){
            sourceEmpty = 'Source is mandatory.';
            valid = false;
        }
        
        return valid;
    }

    /**
    * Method queries if a Lead or Account exists with the same phone.
    * If so and the Rep is the owner of existing lead/account then the page
    * is redirected to the respective lead/account page. If the owner is another
    * rep then a message is displayed on the existing VF page.
    * Else SIL is invoked.
    */  
    public void validateLead(){
        
        Id userId = UserInfo.getUserId();

        List<Lead> existingLeads = new List<Lead>();
        List<Account> existingAccounts = new List<Account>();
    
        if(!NMRUtil.isEmpty(phoneNumber)){
            existingLeads = [select Id, Name, ownerId, NMR_Sales_Rep__c from Lead where (RecordTypeId =: nmrLeadRecordTypeID or RecordTypeId =:nmrLeadCustIdRecordTypeID) and CleanPhone__c =: phoneNumber and IsConverted = false];
            existingAccounts = [select Id, Name, ownerId, OOR_Secondary_Account_Owner__c from Account where RecordTypeId =: nmrAccountRecordTypeID and CleanPhone__c =: phoneNumber];
        }                  
        
        if(existingLeads.size()>0 || existingAccounts.size()>0){
            if(existingLeads.size()>0){// lead exists
                newPageId = existingLeads[0].Id;
                if(userId==existingLeads[0].NMR_Sales_Rep__c || userId==existingLeads[0].ownerId){// same owner
                    dupLeadSameOwner = True;    
                }
                else{//diff owner
                    dupLeadDiffOwner = True;
                }        
            }
            if(existingAccounts.size()>0){// account exists
                newPageId = existingAccounts[0].Id;
                if(userId==existingAccounts[0].OOR_Secondary_Account_Owner__c || userId==existingAccounts[0].ownerId){// same owner    
                    dupAccSameOwner = True;
                }
                else{//diff owner
                    dupAccDiffOwner = True;
                }        
            }    
        }          
        else{
            createLead = true;
            //createLeads();        
        }
    }
    
    /**
    * Method to invoke SIL to create a new SLR
    * 
    **/
    
    
    public void createLeads(){
        if(createLead){
            String customerId = '';
            String slrId = '';
            createLead = false;
            phoneNumber = SilCustomerHelper.CreatePhoneNumberHash(phoneNumber);
            String body = 'leadSource=SFDC&leadType=IFIKI&sourceLeadId=&businessName=' + EncodingUtil.urlEncode(companyName ,'UTF-8') + '&businessPhone=' + phoneNumber + '&state=&zip=';
          
            HttpRequest req= new HttpRequest();       
            req.setMethod('POST');    
            req.setEndpoint(appEndPoint.CWS_End_URL__c + 'LeadService.svc/CreateLead?' + body); 
            req.setHeader('Content-Length','1024');
            req.setBody(body); 
            req.setTimeout(120000);      
            req.setCompressed(true);
            try{        
                Http http = new Http();    
                HttpResponse res= http.send(req);
                system.debug(res.getBody());
                if(res.getStatusCode() == 200){ //success response    
                    showError = false;
                    Dom.Document resDoc = res.getBodyDocument();
                    Dom.XMLNode createLeadResp = resDoc.getRootElement();
                    Dom.XMLNode result = createLeadResp.getChildElement('Result', null);
                    if('Complete'.equalsIgnoreCase(result.getChildElement('LeadStatus', null).getText()))
                    {
                        createLead = true;
                        customerId = result.getChildElement('CustomerId', null).getText();
                        if(NMRUtil.isEmpty(customerId))
                            slrId = result.getChildElement('SalesforceSLRId', null).getText();    
                    }
                    else{  
                       showError = True;
                       errorMessage = 'Lead Status: ' + result.getChildElement('LeadStatus', null).getText();
                    }          
                }
                else{ // error response
                    showError = True;
                    errorMessage = 'Error Code: ' + res.getStatusCode() + '. Error Message: ' + res.getStatus();
                }
                         
            }catch(CalloutException e){       
                system.debug('Exception during lead creation webservice call. Error message: '+e.getMessage());
                showError = True;
                errorMessage = 'Exception during lead creation webservice call. Error message: ' + e.getMessage();
            }catch(Exception e){
                system.debug('Unable to handle data while creating lead. Error message:' + e.getMessage());
                showError = True;
                errorMessage = 'Unable to handle data while creating lead. Error message: ' + e.getMessage();
            }
            
            if(!NMRUtil.isEmpty(customerId)){
                List<Account> accountList = [Select Id, Name from Account where RecordTypeId =: nmrAccountRecordTypeID and CSS_CustomerID__c =: customerId limit 1];
                if(accountList.size()>0)
                    newPageId = accountList[0].Id;
            }else if(!NMRUtil.isEmpty(slrId)){
    
                List<Standardized_Lead_Request__c> slrList = [Select Id, Name, Related_Lead_Id__r.Id from Standardized_Lead_Request__c where Id =: slrId];
                if(slrList.size()>0)
                    newPageId = slrList[0].Related_Lead_Id__r.Id;
                
                List<Lead> leadList = [Select Id, Name from Lead where Id =: newPageId];
                
                if(leadList.size()>0){
                    User userDetails = [Select Id, ManagerId from User where Id =: UserInfo.getUserId()];
                    if(!NMRUtil.isEmpty(userDetails.ManagerId)){
                        leadList[0].ownerId = userDetails.ManagerId;
                        leadList[0].NMR_Sales_Rep__c = userDetails.Id;
                    } else
                        leadList[0].ownerId = userDetails.Id;
                }
                
                if(leadList.size()>0){
                    try{
                        update leadList;
                    } catch(DMLException e){
                        System.debug('LeadCreateExtension: Error assigning the lead. ' + e.getMessage());
                    }
                } 
            }
        }
        
    }
    
        // Test Method
    @isTest(SeeAllData=True)    
    static void myTest() {
          
        test.startTest();
        
        //To Test for existing leads
        Lead lead = new Lead(lastName = 'Test Lead', recordtypeid=RecordTypeHelper.GetRecordTypeID('Lead', 'NMR Lead'), phone='9992995645', company = 'Acc');
        insert lead;
 
        Standardized_Lead_Request__c SLR = new Standardized_Lead_Request__c(Business_Phone__c = '9992995645', company__c = 'testcomp');
   
        ApexPages.StandardController sc = new ApexPages.StandardController(SLR);
        NMRLeadCreateExtension objclass = new NMRLeadCreateExtension(sc);
        objclass.phoneNumber = '9992995645';
        objclass.source = 'Meeting';
        objclass.companyName = 'Accenture';
        objclass.submit();
        
        //To test for existing account
        Profile profile = [select id from profile where name='System Administrator'];         
        User user = new User(alias = 'sysad', email='sysadmin@accenture.com',emailencodingkey='UTF-8', lastname='Admin', languagelocalekey='en_US',localesidkey='en_US', profileid = profile.Id, timezonesidkey='Asia/Calcutta', username='testad123@testorg.com');           
        insert user;  
        
        Account account = new Account(name = 'Test Account', recordtypeid=RecordTypeHelper.GetRecordTypeID('Account', 'CSS Customer'), phone='9992995646', OwnerId = user.Id);
        insert account;
           
        SLR = new Standardized_Lead_Request__c(Business_Phone__c = '9992995646', company__c = 'testcomp');
   
        sc = new ApexPages.StandardController(SLR);
        objclass = new NMRLeadCreateExtension(sc);
        objclass.phoneNumber = '9992995646';
        objclass.source = 'Meeting';
        objclass.companyName = 'Accenture';
        objclass.submit();
        
        //To test for new lead   
        SLR = new Standardized_Lead_Request__c(Business_Phone__c = '9992995647', company__c = 'testcomp');
   
        sc = new ApexPages.StandardController(SLR);
        objclass = new NMRLeadCreateExtension(sc);
        objclass.phoneNumber = '9992995647';
        objclass.source = 'Meeting';
        objclass.companyName = 'Accenture';
        objclass.submit();
        objclass.createLeads();
        
        test.stopTest();
    }
}